package com.txr.news.interceptor;

import com.txr.news.customexception.BusinessException;
import com.txr.news.pojo.ExType;
import com.txr.news.utils.JwtUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class AuthInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String method = request.getMethod();
        if (method.equalsIgnoreCase("options")){
            return true;
        }
        String token = request.getHeader("Authorization");
        if (token == null){
            //无token
            throw new BusinessException("invalid token from interceptor", ExType.BussInvalidToken);
        }
        System.out.println("in preHandle ...");
        if (!JwtUtils.verifyToken(token)){
            //检验为无效token
            System.out.println("token无效");
            throw new BusinessException("invalid token from interceptor", ExType.BussInvalidToken);
        }

        //获取签发对象
        String strId = JwtUtils.getAudience(token);
        // 使用 ThreadLocal
        request.setAttribute("userId",Integer.parseInt(strId));
        //通过拦截器，请求放行
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
